#include <vector>
#include <stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
/*
 * @lc app=leetcode.cn id=145 lang=cpp
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 这个有点捞, 修改了原来的指针
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> recurse;
        vector<int> res;
        if (!root) return res;
        recurse.push(root);
        while (!recurse.empty()) {
            auto x = recurse.top();
            if (!x->left && !x->right) {
                recurse.pop();
                res.push_back(x->val);
                continue;
            }
            if (x->right) recurse.push(x->right);
            if (x->left) recurse.push(x->left);
            x->left = nullptr; x->right = nullptr;
        }
        return res;
    }
};
// @lc code=end

